package servlets;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import users.Subscription;

import dao.ReaderDAO;
import dao.SubscriptionDAO;
import dao.hibernate.ReaderDAOHibernateImpl;
import dao.hibernate.SubscriptionDAOHibernateImpl;

import model.Reader;

/**
 * Servlet implementation class SubscribeServlet.
 */
public class SubscribeServlet extends HttpServlet {
    /** Serial version UID. */
    private static final long serialVersionUID = 1L;
    /** String to join tags. */
    private static final String AND = " AND ";

    /** DAO to modify readers in the database. */
    private ReaderDAO readerDAO;
    /** DAO to modify subscriptions in the database. */
    private SubscriptionDAO subscriptionDAO;

    /**
     * Initializes the servlet.
     *
     * @param config  configuration data of the servlet
     * @throws ServletException  if there is any problem
     */
    @Override
    public void init(final ServletConfig config) throws ServletException {
        super.init(config);

        readerDAO = new ReaderDAOHibernateImpl();
        subscriptionDAO = new SubscriptionDAOHibernateImpl();
    }

    /**
     * Return a view with the available topics in the selected newspapers or
     * the available tags in the selected topics.
     *
     * Return the reader main view if nothing is selected.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doGet(HttpServletRequest request,
     *                           HttpServletResponse response)
     */
    @Override
    protected void doGet(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
//WHEN THERE ARE TAGS
//        if (request.getParameter("isNP") != null) { //1st time: read newspapers
//            String[] selectedNPs = request.getParameterValues("selectedNPs");
//            if (selectedNPs != null) {
//                request.getSession().setAttribute("selectedNPs", selectedNPs);
//                getServletContext().getRequestDispatcher(
//                        "/jsp/selectTopics.jsp").forward(request, response);
//            } else {
//                getServletContext().getRequestDispatcher(
//                        "/jsp/readerMainView.jsp").forward(request, response);
//            }
//        } else { //2nd time: read topics
//            String[] selTopics = request.getParameterValues("selTopics");
//            if (selTopics != null) {
//                request.getSession().setAttribute("selTopics", selTopics);
//                getServletContext().getRequestDispatcher(
//                        "/jsp/selectTags.jsp").forward(request, response);
//            } else {
//                getServletContext().getRequestDispatcher(
//                        "/jsp/readerMainView.jsp").forward(request, response);
//            }
//        }
        
//WHEN THERE ARE NOT TAGS
        String[] selectedNPs = request.getParameterValues("selectedNPs");
        if (selectedNPs != null) {
            request.getSession().setAttribute("selectedNPs", selectedNPs);
            getServletContext().getRequestDispatcher(
                    "/jsp/selectTopics.jsp").forward(request, response);
        } else {
            getServletContext().getRequestDispatcher(
                    "/jsp/readerMainView.jsp").forward(request, response);
        }
    }

    /**
     * Subscribe the reader to the selected topics with the selected tags in
     * the selected newspapers.
     *
     * Return the reader main view.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doPost(HttpServletRequest request,
     *                            HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
//WHEN THERE ARE TAGS
//        String[] selTopics = (String[]) request.getParameterValues("selTopics");
//        if (selTopics != null) {
//            Reader reader
//                    = (Reader) request.getSession().getAttribute("reader");
//            for (String topic : selTopics) {
//                String tagArrayName = "selTags" + topic;
//                String[] selTags
//                        = (String[]) request.getParameterValues(tagArrayName);
//                String msgSelector = "";
//                if (selTags != null) {
//                    msgSelector += selTags[0];
//                    for (int i = 1; i < selTags.length; i++) {
//                        msgSelector += AND;
//                        msgSelector += selTags[i];
//                    }
//                }
//                Subscription subscription
//                        = reader.addSubscription(topic, msgSelector);
//
//                if (subscription != null) {
//                    subscriptionDAO.saveSubscription(subscription);
//                    readerDAO.updateReader(reader);
//                }
//
//                System.out.println("Reader subscribed to topic " + topic
//                                   + " with message selector " + msgSelector);
//            }
//        }
//        getServletContext().getRequestDispatcher("/jsp/readerMainView.jsp")
//                .forward(request, response);

//WHEN THERE ARE NOT TAGS
        String[] selTopics
                = (String[]) request.getParameterValues("selTopics");
        if (selTopics != null) {
            Reader reader 
                    = (Reader) request.getSession().getAttribute("reader");
            for (String topic : selTopics) {
                Subscription subscription
                        = reader.addSubscription(topic, null);

                if (subscription != null) {
                    subscriptionDAO.saveSubscription(subscription);
                    readerDAO.updateReader(reader);
                }

                System.out.println("Reader subscribed to topic " + topic);
            }
        }
        getServletContext().getRequestDispatcher("/jsp/readerMainView.jsp")
                .forward(request, response);
    }

}
